package com.zecan.rabbitmq.rabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: lenovo
 * \* Date: 2022/4/21
 * \* Time: 9:12
 * \* Description:
 * \
 */
@Component
@Slf4j
public class MyCallBackConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {


    @Resource
    private RabbitTemplate rabbitTemplate;


    // 将当前类作为回调类注入到rabbit中
    @PostConstruct
    public void setCallBack() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    /**
     * rabbitmq 的回调方法
     *
     * @param correlationData 消息的相关数据
     * @param ack             交换机是否接收到消息 收到为true  失败为false
     * @param s               失败的原因, 发送成功则为null
     * @return void
     * @author
     * @date 2022/4/21
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String s) {
        String id = correlationData != null ? correlationData.getId() : "";
        if (ack) {
            log.info("交换机已经收到 id 为:{}的消息", id);
        } else {
            log.info("交换机还未收到 id 为:{}消息,由于原因:{}", id, s);
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.error("当前消息{}被退回到交换机{},原因{},连接的路由{}",
                new String(returnedMessage.getMessage().getBody()),
                returnedMessage.getExchange(),
                returnedMessage.getReplyText(),
                returnedMessage.getRoutingKey());
    }
}
